package com.atguigu.gulimall.order.service.impl;

import com.atguigu.gulimall.order.entity.OrderEntity;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.order.dao.OrderItemDao;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.service.OrderItemService;


@Service("orderItemService")
@RabbitListener(queues = {"atguigu.hello.queue"})
public class OrderItemServiceImpl extends ServiceImpl<OrderItemDao, OrderItemEntity> implements OrderItemService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderItemEntity> page = this.page(
                new Query<OrderItemEntity>().getPage(params),
                new QueryWrapper<OrderItemEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 监听队列的消息
     * 参数
     *      org.springframework.amqp.core.Message
     *      T 发送过来的消息类型
     *      Channel channel 传输数据的通道
     * 1 一个消息只能一个客户端收到，接收后从对列中删除
     *
     *
     * @param message
     */
    @RabbitListener(queues = {"atguigu.hello.queue"})
    @RabbitHandler
    public void recieve(Message message, OrderItemEntity orderItemEntity, Channel channel){
        // 获取 deliveryTag
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            if (deliveryTag%2==0){
                System.out.println("签收完成" + deliveryTag);
                // 签收
                channel.basicAck(deliveryTag,false);
                byte[] body = message.getBody();
                System.out.println("消息是 OrderItemEntity ： " + orderItemEntity);
            }else {
                System.out.println("签收失败" + deliveryTag);
                // 拒签
                channel.basicNack(deliveryTag,false,false);

            }

        } catch (IOException e) {
            e.printStackTrace();
        }



    }

//    @RabbitHandler
    public void recieve(OrderEntity orderEntity, Channel channel){
        System.out.println("消息是 orderEntity ： " + orderEntity);

    }
}